package com.digital.library.common.interceptors;

import com.alibaba.fastjson.JSON;
import com.digital.library.common.constant.CommonConstant;
import com.digital.library.common.utils.JwtUtil;
import com.digital.library.common.utils.ObjectConvertUtil;
import com.digital.library.common.vo.Result;
import com.digital.library.modules.system.domain.SysUser;
import com.digital.library.modules.system.service.SysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 用户认证类
 */
public class AuthInterceptor implements HandlerInterceptor {

    private final static Logger logger = LoggerFactory.getLogger(AuthInterceptor.class);

    @Autowired
    SysUserService sysUserService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
        if(ObjectConvertUtil.isEmpty(token)) {
            this.backError(response,"token为空！");
            return false;
        }else{
            String username = JwtUtil.getUsername(token);
            if (username == null) {
                this.backError(response,"token非法无效！");
                return false;
            }

            // 查询用户信息
            SysUser user = sysUserService.getUserByName(username);
            if (user == null) {
                this.backError(response,"用户不存在！");
                return false;
            }
        }

        return true;
    }

    /**
     * 返回一个错误信息
     *
     * @param response
     */
    private void backError(HttpServletResponse response, String errMess) {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        response.setHeader("auth", "fail");
        try {
            writer = response.getWriter();
            Result<?> result = Result.error(errMess);
            writer.print(JSON.toJSON(result));
        } catch (IOException e) {
            logger.error(e.getMessage());
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }
}
